﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RMS.Models;
using RMS.Models.Repository;
using RMS.Pages.Helpers;
using System.Web.Routing;

namespace RMS.Pages
{
    public partial class Listing : System.Web.UI.Page
    {
        private Repository repo = new Repository();
        private int pageSize =3; // number of items per page
               
        /*We locate the id value of the required retreat from the form data that we receive and use the repository to retrieve the 
         * corresponding Retreat object. Using the SessionHelper class, we obtain the Cart associated 
         * with the user’s session and add the selected retreat to it. */

        protected void Page_Load(object sender, EventArgs e) {
            if (IsPostBack) {

                int selectedRetreatId;
                if (int.TryParse(Request.Form["add"], out selectedRetreatId)) {
                    
                    Retreat selectedRetreat = repo.Retreats
                    .Where(p => p.Ret_ID == selectedRetreatId).FirstOrDefault();
                    
                    if (selectedRetreat != null) {
                        SessionHelper.GetCart(Session).AddItem(selectedRetreat, 1);
                        SessionHelper.Set(Session, SessionKey.RETURN_URL,
                        Request.RawUrl);
                        Response.Redirect(RouteTable.Routes
                        .GetVirtualPath(null, "cart", null).VirtualPath);
                    }
                }
            }
        }

        // All we have to do to bring the contents of our database into the code-behind class is 
        // create a new instance of the Repository class and read the Retreats property.
        public IEnumerable<Retreat> GetRetreats() {
            return FilterRetreats() // old: return repo.Retreats
            .OrderBy(p => p.Ret_Title)          // For Pagination
            .Skip((CurrentPage - 1) * pageSize)
            .Take(pageSize); // select the quantity of Retreat objects we show to the user
        }

        protected int CurrentPage {
            get {
                              
                int page = GetPageFromRequest();
                return page > MaxPage ? MaxPage : page;
            }
        }
        
        // The MaxPage property returns the largest page value for which we can display products.
        protected int MaxPage {
            get {
                int retCount = FilterRetreats().Count();
                return (int)Math.Ceiling((decimal)retCount / pageSize);
            }
        }

        // Method provides filtering for retreats based on category
        private IEnumerable<Retreat> FilterRetreats()
        {
            IEnumerable<Retreat> retreats = repo.Retreats;
            string currentCategory = (string)RouteData.Values["category"] ??
            Request.QueryString["category"];
            // return currentCategory == null ? retreats : retreats.Where(p => p.Ret_Main_Category == currentCategory);
            return currentCategory == null ? retreats : retreats.Where((p => (p.Ret_Main_Category == currentCategory) || (p.Ret_Category_Two == currentCategory)
                                                                    || (p.Ret_Category_Three == currentCategory) || (p.Ret_Category_Four == currentCategory) ));
        }
        
        // For URL Routing
        // We get routing variables through the RouteData.Values collection.
        private int GetPageFromRequest()
        {
            int page;
            string reqValue = (string)RouteData.Values["page"] ??
                Request.QueryString["page"]; // check the Request.QueryString properties if there isn’t a routing variable available
            return reqValue != null && int.TryParse(reqValue, out page) ? page : 1;
        }

        // Formats dates for retreat listings (utilizes | as delimeter)
        public string dateFormat(string input)
        {
            string str = input;
            Boolean notValid = true;
            int num;
            int count = 0;
            string temp = "";

            while (notValid) {
                
                num = str.IndexOf('|', 0);

                if (num == -1) {
                    if (count == 0)
                    {
                        temp = "<h5>" + str + "</h5>";
                    }
                    else
                    {
                        temp += "<h5>" + str + "</h5>";
                    }
                                       
                    notValid = false;
                }
                else {
                     temp += "<h5>" + str.Substring(0, num) + "</h5>";
                     str = str.Substring(num+1);
                }

                count++;
            }
           
            return temp;
        }
        
    }
}